var table;
$(function () {
    initTable();

    $("#tr-select-all").on('click', function () {
        if ($(this).prop("checked")) {
            $('#table tbody .tr-checkbox:not(:checked)').click();
        } else {
            $('#table tbody .tr-checkbox:checked').click();
        }
    });

    $('#table tbody').on('click', '.tr-checkbox', function () {
        if ($(this).prop("checked")) {
            $(this).closest("tr").addClass("tr-selected");
        } else {
            $(this).closest("tr").removeClass("tr-selected");
        }
    });
});

function nullToString(obj) {
    if (typeof (obj) == "undefined" || obj == null || obj === "") {
        return "";
    } else {
        return obj;
    }
}

function fixToString(str) {
    if (str == "()") {
        return "";
    } else {
        return str.length >= 200 ? str.substr(0, 200) + "......" : str;
    }
}

function getParam(data) {
    var param = {};
    param.job = $("#job").val();
    param.district = $("#district").val();
    param.name = $("#name").val();
    param.mobileNumber = $("#mobile_number").val();
    param.draw = data.draw;
    param.size = data.length;
    param.current = (data.start / data.length) + 1;//当前页码
    param.pageType = "show";
    return param;
}

function getSelectTrId() {
    var factorId = [];
    $(".tr-selected").each(function () {
        var id = $(this).attr("data-id");
        factorId.push(id);
    });
    return factorId;
}

//查询方法
function queryData() {
    table.ajax.reload();
}

//重置方法
function resetData() {
    $("#job").val("");
    $("#district").val("");
    $("#name").val("");
    $("#mobile_number").val("");
}

//下载方法
function downloadData() {
    if ($(".tr-selected").length > 1) {
        var data = getSelectTrId();
        location.href += "/show/downloadAll?idList=" + data;
    } else if ($(".tr-selected").length == 1) {
        location.href += "/show/download?id=" + $(".tr-selected").attr("data-id");
    } else {
        alert("请至少选择一行!");
    }
}

//预览方法
function preview(td) {
    var id = $(td).attr("data-file-id")
    $.ajax({
        type: "get",
        url: ctp + "/edit/openUrl?fileId=" + id,
        cache: false,
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            if (result.code == "200") {
                var filePath = ctp + "/static" + result.data.filePath.substring(result.data.filePath.lastIndexOf("upload") - 1);
                window.open(filePath.replace(/\\/g, "/"));
            } else {
                alert(result.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络异常");
        }
    });
}

//初始化方法
function initTable() {
    table = $('#table').DataTable({
        deferRender: true,
        serverSide: true,
        searching: false,
        ordering: false,
        sort: true,
        searchDelay: 200,
        autoWidth: true,
        processing: true,
        pageLength: 25,
        renderer: "bootstrap",
        pagingType: "full_numbers", //分页样式：simple,simple_numbers,full,full_numbers
        ajax: function (data, callback, settings) {
            $.ajax({
                type: "post",
                url: ctp + "/show/list",
                cache: false,
                data: JSON.stringify(getParam(data)),
                dataType: "json",
                contentType: "application/json",
                success: function (result) {
                    if (result.code == "200") {
                        var returnData = {};
                        returnData.draw = result.draw;//这里直接自行返回了draw计数器,应该由后台返回
                        returnData.recordsTotal = result.data.total;//返回数据全部记录
                        returnData.recordsFiltered = result.data.total;//后台不实现过滤功能，每次查询均视作全部结果
                        returnData.data = result.data.records;//返回的数据列表
                        callback(returnData);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("网络异常");
                }
            });
        },
        columns: [
            {
                "data": "rowNum",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return "<input type='checkbox' class='tr-checkbox' >";
                },
                "width": "35px"
            },
            {
                "data": "title",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return fixToString(nullToString(full.job) + "(" + nullToString(full.district) + ")");
                },
            },
            {
                "data": "name",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                },
                "width": "70px"
            },
            {
                "data": "mobileNumber",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                },

            },
            {
                "data": "salary",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                },
                "bSortable": true
            },
            {
                "data": "preliminaryDescription",
                "className": 'text-left',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            },
            {
                "data": "operationStatus",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return getOperationStatusInfo(data);
                }
            },
            {
                "data": "openUrl",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return "<a href='javascript:void(0);'  data-file-id='" + full.fileId + "' class='btn btn-sm btn-link' onclick='preview(this)'> 预览</a>";
                },
                "width": "50px"
            }
        ],
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 项",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
            "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页",
                "sJump": "跳转"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        createdRow: function (row, data, dataIndex) {
            $(row).attr("data-id", data.id);
            $(row).attr("data-file-id", data.fileId);
            $(row).attr("data-status", data.status);
        },
        dom: "<'row'<'col-sm-2'l><'col-sm-2'r><'#tools.col-sm-8 text-right'>>" +
            "t" +
            "<'row'<'col-sm-4'i><'col-sm-8'p>>",
        initComplete: function () {
            $("#tools").append('<button type="button" id="btn_downloadData" class="btn btn-primary btn-sm"><span class="oi oi-cloud-download" title="cloud-download" aria-hidden="true"></span> 下载</button>');
            $("#tools").append('<button type="button" id="btn_queryData" class="btn btn-info btn-sm"><span class="oi oi-magnifying-glass" title="magnifying-glass" aria-hidden="true"></span> 搜索</button>');
            $("#tools").append('<button type="button" id="btn_resetData" class="btn btn-outline-secondary btn-sm">重置</button>');
            //查询按钮  btn_queryData
            $('#btn_downloadData').on("click", function () {
                downloadData()
            });
            //查询按钮  btn_queryData
            $('#btn_queryData').on("click", function () {
                queryData();
            });
            //重置按钮  btn_queryData
            $('#btn_resetData').on("click", function () {
                resetData();
            });
        }
    });
}

//简历标记：0 待面试 1 已录取,2 储备,3 不合适
function getOperationStatusInfo(obj) {
    if (obj == 0) {
        return "待面试";
    } else if (obj == 1) {
        return "已录取";
    } else if (obj == 2) {
        return "储备";
    } else if (obj == 3) {
        return "不合适";
    } else {
        return "待面试";
    }
}

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}


